package cn.auth.controller;

import cn.auth.config.web.ResponseMessage;
import cn.auth.config.web.ResponseStatusCode;
import cn.auth.pojo.User;
import cn.auth.service.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 毛苏宇
 * User: me
 * Date: 2020/6/26
 * Time: 2:08
 * Description:
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseMessage login(User user, HttpServletResponse response) {
        //先去数据库中查询用户是否存在
        final boolean exists = userService.existsByUserName(user.getUsername());
        if (exists) {
            //验证用户名和密码
            final User u = userService.find(user);
            if (null != u) {
                Map<String, Object> claims = new HashMap<>(5);
                claims.put("jwtId", u.getUserId());
                claims.put("jwtIdentity", u.getIdentity());
                claims.put("jwtUsername", u.getUsername());
                //创建jwt
                String jwtToken = Jwts.builder()
                        //该JWT面向的对象,也就是这个jwt是哪个用户的
                        .setSubject(u.getUsername())
                        //将用户数据填充到jwt
                        .setClaims(claims)
                        //JWT签署时间
                        .setIssuedAt(new Date())
                        //JWT使用的签名算法
                        .signWith(SignatureAlgorithm.HS256, "secretkey").compact();
                response.addHeader("jwtToken", jwtToken);
                return new ResponseMessage(ResponseStatusCode.CODE_SUCCESS, "登录成功", u.getUserId());
            }
            return new ResponseMessage(ResponseStatusCode.CODE_FAIL, "登陆失败", null);
        }
        return new ResponseMessage(ResponseStatusCode.CODE_NOT_EXISTS, "用户不存在", null);
    }

    @PostMapping("/create")
    public ResponseMessage create(User user) {
        long addUser = userService.add(user);
        if (addUser > -1) {
            return new ResponseMessage(ResponseStatusCode.CODE_SUCCESS, "用户创建成功", user.getUserId());
        }
        return new ResponseMessage(ResponseStatusCode.CODE_FAIL, "用户创建失败", null);
    }

    @PostMapping("/update")
    public ResponseMessage update(User user) {
        final boolean modify = userService.modify(user);
        if (modify) {
            return new ResponseMessage(ResponseStatusCode.CODE_SUCCESS, "信息修改成功", null);
        }
        return new ResponseMessage(ResponseStatusCode.CODE_FAIL, "信息修改失败", null);
    }

    @PostMapping("/delete")
    public ResponseMessage delete(@RequestParam("userId") long userId) {
        final boolean remove = userService.remove(userId);
        if (remove) {
            return new ResponseMessage(ResponseStatusCode.CODE_SUCCESS, "用户删除成功", null);
        }
        return new ResponseMessage(ResponseStatusCode.CODE_FAIL, "用户删除失败", null);
    }

    @PostMapping("list")
    public ResponseMessage list(@RequestParam(value = "page", defaultValue = "1") int page,
                                @RequestParam(value = "rows", defaultValue = "5") int rows) {
        return new ResponseMessage(ResponseStatusCode.CODE_SUCCESS, "请求成功", userService.findUsers(page, rows));
    }

}
